package com.lineage.server.timecontroller.pc;

import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.thread.GeneralThreadPool;
import com.lineage.server.thread.PcOtherThreadPool;
import com.lineage.server.world.World;
import java.util.Collection;
import java.util.Iterator;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class Auto_Time extends TimerTask {
  private static final Log _log = LogFactory.getLog(Auto_Time.class);
  
  private ScheduledFuture<?> _timer;
  
  public void start() {
    int timeMillis = 1000;
    this._timer = GeneralThreadPool.get().scheduleAtFixedRate(this, timeMillis, timeMillis);
  }
  
  public void run() {
    try {
      Collection<L1PcInstance> all = World.get().getAllPlayers();
      if (all.isEmpty())
        return; 
      Iterator<L1PcInstance> iter = all.iterator();
      while (iter.hasNext()) {
        L1PcInstance tgpc = iter.next();
        int time = tgpc.get_other().get_Auto_Points();
        if (time > 0 && tgpc.isActived()) {
          time--;
          check(tgpc, Integer.valueOf(time));
          Thread.sleep(1L);
        } 
      } 
    } catch (Exception e) {
      _log.error("PC 挂机处理时间轴异常重启", e);
      PcOtherThreadPool.get().cancel(this._timer, false);
      Auto_Time autoTimer = new Auto_Time();
      autoTimer.start();
    } 
  }
  
  private static void check(L1PcInstance tgpc, Integer time) {
    if (time.intValue() > 0) {
      tgpc.get_other().set_Auto_Points(time.intValue());
    } else {
      tgpc.get_other().set_Auto_Points(0);
      if (tgpc.getNetConnection() != null)
        outPc(tgpc); 
    } 
  }
  
  private static void outPc(L1PcInstance tgpc) {
    try {
      if (tgpc != null)
        tgpc.endAuto(); 
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
  }
}
